package edu.jimei.projecttachy.service;

import edu.jimei.projecttachy.entity.DataSource;
import edu.jimei.projecttachy.entity.ReportTask;
import edu.jimei.projecttachy.repository.DataSourceRepository;
import edu.jimei.projecttachy.repository.ReportTaskRepository;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class ReportTaskService {

    private final ReportTaskRepository reportTaskRepository;
    private final DataSourceRepository dataSourceRepository;
    private final ChatClient chatClient;

    @Autowired
    public ReportTaskService(ReportTaskRepository reportTaskRepository, DataSourceRepository dataSourceRepository, ChatClient.Builder chatClientBuilder) {
        this.reportTaskRepository = reportTaskRepository;
        this.dataSourceRepository = dataSourceRepository;
        this.chatClient = chatClientBuilder.build();
    }

    public List<ReportTask> findAll() { return reportTaskRepository.findAll(); }
    public Optional<ReportTask> findById(Long id) { return reportTaskRepository.findById(id); }
    public ReportTask save(ReportTask task) { return reportTaskRepository.save(task); }

    @Transactional
    public void refreshReportTask(Long taskId) {
        // 1. Find the report task
        ReportTask reportTask = reportTaskRepository.findById(taskId)
                .orElseThrow(() -> new EntityNotFoundException("ReportTask not found with id: " + taskId));

        // 2. Mark as processing
        reportTask.setStatus("Processing");
        reportTaskRepository.save(reportTask);

        // 3. Get the associated data source directly from the report task
        DataSource dataSource = reportTask.getDataSource();
        if (dataSource == null) {
            throw new IllegalStateException("ReportTask with id " + taskId + " does not have an associated data source.");
        }

        // 4. Build the prompt for the AI
        String prompt = String.format(
                "Please generate a detailed analysis report based on the following data source information.\n" +
                "Data Source Name: %s\n" +
                "Data Source Type: %s\n" +
                "Your analysis should summarize the key points and provide actionable insights.",
                dataSource.getName(),
                dataSource.getType()
        );

        // 5. Call AI service
        String newContent = chatClient.prompt()
                .user(prompt)
                .call()
                .content();

        // 6. Update the report task with the new content and mark as completed
        reportTask.setContent(newContent);
        reportTask.setStatus("Completed");
        reportTaskRepository.save(reportTask);
    }
} 